package com.axend.aerosense.dev.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.base.IHostLayout;
import com.axend.aerosense.common.base.ITitle;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.connect.DeviceConnectManager;
import com.axend.aerosense.common.connect.bean.BleMsgTag;
import com.axend.aerosense.common.connect.bean.BleNotifyEntity;
import com.axend.aerosense.common.connect.bean.DeviceConnectType;
import com.axend.aerosense.common.connect.bean.MessageEntity;
import com.axend.aerosense.common.connect.bean.WifiScanResultBean;
import com.axend.aerosense.common.connect.impl.IScanCallback;
import com.axend.aerosense.common.connect.impl.IScanResult;
import com.axend.aerosense.common.connect.tcp.IDeviceConnectCallback;
import com.axend.aerosense.common.ui.CustomTipsDialog;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.common.util.SendMessageUtil;
import com.axend.aerosense.dev.BR;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.activity.DevBaseWifiActivity;
import com.axend.aerosense.dev.activity.NewDevSetNetActivity;
import com.axend.aerosense.dev.databinding.DevFragmentInputWifiBinding;
import com.axend.aerosense.dev.entity.RadarNetworkBean;
import com.axend.aerosense.dev.viewmodel.FamilyWifiViewModel;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DevFamilyWifiFragment
        extends MvvmBaseFragment<DevFragmentInputWifiBinding, FamilyWifiViewModel>
        implements ILoadDataResult<RadarNetworkBean>, IScanCallback, IDeviceConnectCallback {

    private List<Map<String, Object>> listMap;
    private Activity mActivity;
    private DeviceConnectManager connectManager;
    private DeviceConnectType connectType;

    private Bundle bundle;
    private RadarType radarType;
    private BleNotifyEntity wavveDeviceInfo;
    private SendMessageUtil sendMessageUtil;

    public static DevFamilyWifiFragment getInstance(){
        DevFamilyWifiFragment fragment = new DevFamilyWifiFragment();
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView() {
        bundle = getArguments();
        if (bundle != null){
            radarType = (RadarType) bundle.getSerializable(DevChooseDeviceFragment.RADAR_TYPE);
        }
        if (radarType != null){
            viewModel.radarType = radarType;
        }
        connectManager = getWifiActivity().getDeviceConnectManager();
        connectType = connectManager.getConnectType();
        sendMessageUtil = new SendMessageUtil(connectManager, connectType);

        //viewDataBinding.devSpinner.setDropDownVerticalOffset(DisplayUtils.dip2px(45));
        //下一步按钮
        viewDataBinding.devNext.setOnClickListener(v->{
            if (viewModel.pageState.getValue() == 3){
                //雷达联网失败，重新设置
                viewModel.setPageState(0);
                backToFirstPager(false);
                return;
            }

            String ssid = listMap.get(viewDataBinding.devSpinner.getSelectedItemPosition())
                    .get("name")
                    .toString();
            String password = viewDataBinding.devInputPwd.getText().toString().trim();
            if (!"".equals(ssid)){
//                if (getActivity() instanceof NewDevSetNetActivity) {
//                    ((NewDevSetNetActivity) getActivity()).enableBack(false);
//                }
                wavveDeviceInfo = null;
                viewModel.setPageState(2);
                //radarProvide.setFamilyWifiInfo(ssid, password);
                if (connectType == DeviceConnectType.TYPE_WIFI){
                    // wifi模式连接方式
//                    wifiModeMessageQueue.offer(new MessageEntity(MessageEntity.MsgTag.setFamilyWifiInfo ,ssid + "," + password));
                    //当没有wifi密码时，发送“NONE”指令
                    if (TextUtils.isEmpty(password)) {
                        password = "NONE";
                    }
                    sendMessageUtil.initQueue(new MessageEntity(MessageEntity.MsgTag.setFamilyWifiInfo ,ssid + "," + password));
                    connectManager.connectWifi(bundle.getString(DevConnectWifiFragment.DEVICE_SSID));
                }else {
                    //蓝牙模式连接方式
//                    bleModeMessageQueue.offerFirst(new BleMessageEntity(BleMessageEntity.Tag.networkInfo, ssid + "," + password));
                    sendMessageUtil.initQueue(ssid, password, radarType);
                    connectManager.connectBluetooth(radarType);
                }
            }else {
                //ToastUtils.showShort(R.string.dev_input_wifi_password_tip);
            }
        });
        //重新扫描
        viewDataBinding.devReScan.setOnClickListener(v -> {
            if (getWifiActivity().isEnableWifi()){
                viewModel.setPageState(1);
                connectManager.reScanWifi();
            }else {
                viewModel.setPageState(0);
                ToastUtils.showShort(R.string.dev_scan_wifi_failed);
            }
        });

        //如果雷达联网成功，跳转到下一页
        viewModel.isRadarConnectNetSuccess.observe(getViewLifecycleOwner(), aBoolean -> {
            if (aBoolean){
                toNextPage();
            }
        });

        viewModel.pageState.observe(getViewLifecycleOwner(), integer -> {
            viewDataBinding.devImage.setImageResource(integer != 3 ? R.mipmap.dev_connect_hot : R.mipmap.dev_img_connection_failed);
        });
        getWifiList();
    }

    //初始化命令列表
//    private void initCommandList(){
//        if (connectMode == DeviceConnectManager.CONNECT_MODE_WIFI){
//            wifiModeMessageQueue = new LinkedList<>();
//            wifiModeMessageQueue.offer(new MessageEntity(MessageEntity.MsgTag.getID));
//            wifiModeMessageQueue.offer(new MessageEntity(MessageEntity.MsgTag.setDeviceIPAndPort, UrlApi.assureRadarServerUrl));
//            wifiModeMessageQueue.offer(new MessageEntity(MessageEntity.MsgTag.getHardwareVersion));
//        }else {
//            /**
//             * WAVVE雷达设置完服务器端口和IP后，主动关闭蓝牙，并联网
//             */
////            bleModeMessageQueue = new LinkedList<>();
////            bleModeMessageQueue.offer(new BleMessageEntity(BleMessageEntity.Tag.getDeviceUUID));
////            bleModeMessageQueue.offer(new BleMessageEntity(BleMessageEntity.Tag.serverInfo, UrlApi.wavveRadarServerUrl));
//        }
//    }

    private DevBaseWifiActivity getWifiActivity(){
        FragmentActivity activity = getActivity();
        if (activity instanceof DevBaseWifiActivity) {
            return (DevBaseWifiActivity) activity;
        }
        return null;
    }

    /** 设备连接成功或失败回调 */
    @Override
    public void isConnectSuccess(boolean isSuccess) {
        if (connectType == DeviceConnectType.TYPE_WIFI){
            if (!isSuccess){
                //如果不是在雷达联网等待界面，则视为TCP连接意外断开
//                if (viewModel.pageState.getValue() != 2){
                if (!sendMessageUtil.isEmpty()){
                    getActivity().runOnUiThread(() -> {
                        ToastUtils.showLong(R.string.dev_connect_device_failed);
                        viewModel.setPageState(3);
//                        backToFirstPager(true);
                    });
                }
            }else {
                viewModel.setPageState(2);
                sendMessageUtil.startSend();
//                sendMessage();
            }
        }else {
            //蓝牙连接回调
            if (isSuccess){
//                 sendMessage();
                sendMessageUtil.startSend();
            }else {
//                if (bleModeMessageQueue != null && bleModeMessageQueue.size() != 0){
//                    ToastUtils.longToast(R.string.dev_connect_device_failed);
//                    viewModel.setPageState(0);
//                }
                if (!sendMessageUtil.isEmpty()){
                    ToastUtils.showLong(R.string.dev_connect_device_failed);
                    viewModel.setPageState(3);
                }
            }
        }
    }

    /** 设备数据回调 */
    @Override
    public void deviceData(Object message) {
        //String hexStr = ByteUtils.bytesToHexString(data);
        if (message == null) return;
        if (message instanceof MessageEntity){
            MessageEntity entity = (MessageEntity) message;
            switch (entity.getTag()){
                case getID:
                    String id = entity.getBodyObj().toString();
                    viewModel.radarId = id;
                    LogUtils.d("雷达id：" + id);
                    sendMessageUtil.executed();
                    break;
                case getHardwareVersion:
                    String hardwareVersion = entity.getBodyObj().toString();
                    viewModel.radarVersion = hardwareVersion;
                    LogUtils.d("固件版本：" + hardwareVersion);
                    sendMessageUtil.executed();
                    break;
                case setFamilyWifiInfo :
                    //设置雷达WIFI账号与密码
                    if ((boolean)entity.getBodyObj()){
//                    if (target.equals(DevDeviceSettingsFragment.TARGET_RESET_PARAMETER)){
//                        ToastUtils.longToast(R.string.dev_reset_parameter_success);
//                        ((DevBaseWifiActivity) getActivity()).closeDeviceConnect();
//                        toNextPage();
//                    }else {
//                        viewModel.getRadarStatus();
//                    }
//                        connectManager.close();
//                        viewModel.getRadarStatus();
                        LogUtils.d("设置wifi账号和密码成功！");
                        sendMessageUtil.executed();
                    }else {
                        ToastUtils.showLong(R.string.room_set_fail);
                    }
                    break;
                case setDeviceIPAndPort:
                    //设置雷达IP地址与端口
                    if ((boolean)entity.getBodyObj()){
                        LogUtils.d("设置端口和IP成功！");
                        sendMessageUtil.executed();
                    }else {
                        ToastUtils.showLong(R.string.room_set_fail);
                    }
                    break;
            }
        }else {
            BleNotifyEntity notifyEntity = (BleNotifyEntity) message;
            if (wavveDeviceInfo == null && notifyEntity.getTag() == BleMsgTag.GET_DEVICE_ID){
                wavveDeviceInfo = notifyEntity;
//                viewModel.radarType = radarType.get();
//                viewModel.radarTypeName = radarType.getNameByString();
                viewModel.radarId = wavveDeviceInfo.getData().toString();
                viewModel.radarVersion = "00.00.00.00";
//                sendMessage();
                sendMessageUtil.executed();
                LogUtils.d("收到设备ID:", notifyEntity);
            }
            if (notifyEntity.getTag() == BleMsgTag.SET_STATUS){
//                sendMessage();
                sendMessageUtil.executed(notifyEntity);
                LogUtils.d("设置成功:", notifyEntity);
            }
        }
        if (sendMessageUtil.isEmpty()){
            viewModel.getRadarStatus();
            sendMessageUtil.stopSend();
            connectManager.close();
            LogUtils.d("命令发送完成");
        }
    }

//    private void sendMessage(){
//        ThreadPoolUtils.getInstance().execute(() -> {
//            try {
//                TimeUnit.SECONDS.sleep(1);
//                if (connectMode == DeviceConnectManager.CONNECT_MODE_WIFI){
//                    MessageEntity temp = null;
//                    if ((temp = wifiModeMessageQueue.poll()) != null){
//                        connectManager.sendMessage(temp);
//                    }
//                }else {
                    // 蓝牙模式发送数据
//                    BleMessageEntity ble = null;
//                    if ((ble = bleModeMessageQueue.poll()) != null){
//                        connectManager.sendMessage(ble);
//                    }else {
//                        //命令发完了，进行下一步操作
//                        viewModel.getRadarStatus();
//                        connectManager.close();
//                        LogUtils.d("命令发送完成");
//                    }
//                }
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        });
//    }

    //去下一页
    private void toNextPage(){
//        if (target.equals(DevDeviceSettingsFragment.TARGET_RESET_PARAMETER)) {
//            backToFirstPager(false);
//        }else {
//        }
        viewModel.setPageState(0);
        Fragment fragment = DevBindRoomFragment.getInstance();
        Bundle bundle = new Bundle();
        bundle.putSerializable(DevChooseDeviceFragment.RADAR_TYPE, radarType);
        bundle.putString(DevDeviceSettingsFragment.RADAR_ID, viewModel.radarId);
        fragment.setArguments(bundle);
        FragmentUtil.add(getActivity(), ((IHostLayout)getActivity()).getContentId(), fragment, this, true);
    }

    //返回到第一个页面
    private void backToFirstPager(boolean isConnectBroken){
        if (isConnectBroken){
            LiveDatabus.getInstance()
                    .with(Gobal.EVENT_KEY.CONNECT_BROKEN, Boolean.class)
                    .postValue(true);
        }
        if (getActivity() instanceof NewDevSetNetActivity) {
            ((NewDevSetNetActivity) getActivity()).enableBack(true);
        }

        getActivity().onBackPressed();

//        FragmentManager.BackStackEntry entry = getActivity().getSupportFragmentManager().getBackStackEntryAt(0);
//        int id = entry.getId();
//        getActivity().getSupportFragmentManager().popBackStack(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    /** 显示是否取消添加设备提示框 */
    private void showBackDialog(){
        CustomTipsDialog dialog = new CustomTipsDialog(getContext(), getString(R.string.dev_cancel_add_device));
        dialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                //确定按钮，关闭此Activity，回到主页
                dialog.dismiss();
                getActivity().finish();
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void getWifiList(){
        if (getWifiActivity().isEnableWifi()){
            viewModel.setPageState(1);
            connectManager.scanWifi();
        }else {
            viewModel.setPageState(0);
            ToastUtils.showLong(R.string.dev_scan_wifi_failed);
        }
    }

    private void setDataList(List<IScanResult> dataList){
        if ((dataList.size() == 0 || dataList.isEmpty() || dataList == null) && !isResumed()){
            return;
        }
        listMap = new ArrayList<>();
        //listMap.add(getSpinnerItem(getString(R.string.dev_please_choose)));
        for (int i = 0; i < dataList.size(); i++){
            if(dataList.get(i).getName().indexOf("AS_") == -1){
                listMap.add(getSpinnerItem(dataList.get(i).getName()));
            }
        }
        //手动添加
        //listMap.add(getSpinnerItem(getString(R.string.dev_manually_add)));
        SimpleAdapter simpleAdapter = new SimpleAdapter(mActivity,
                listMap,
                R.layout.dev_layout_spinner_item,
                new String[]{"name"},
                new int[]{R.id.dev_wifi_name}
        );
        viewDataBinding.devSpinner.setAdapter(simpleAdapter);
    }

    private Map<String, Object> getSpinnerItem(String str){
        Map<String, Object> item = new HashMap<>();
        item.put("name", str);
        return item;
    }

    @Override
    public void scanResult(List<IScanResult> list) {
        LogUtils.d("wifiList:" + list);

        if (null == list || list.isEmpty()) {
            return;
        }

        if (list.get(0) instanceof WifiScanResultBean) {
            setDataList(list);
            if (viewModel.pageState.getValue() == 1){
                viewModel.setPageState(0);
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        ((ITitle)getActivity()).setTitle(getString(R.string.dev_input_famly_hot));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        connectManager.close();
        sendMessageUtil.stopSend();
        sendMessageUtil = null;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity=activity;
    }

    @Override
    public int getLayoutId() {
        return R.layout.dev_fragment_input_wifi;
    }

    @Override
    public int getBindingVariable() {
        return BR.viewmodel;
    }

    @Override
    protected FamilyWifiViewModel getViewModel() {
        BaseViewModelFactroy<RadarNetworkBean> factroy = new BaseViewModelFactroy<RadarNetworkBean>(this, this);
        return new ViewModelProvider(this, factroy).get(FamilyWifiViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    public void loadDataSuccess(RadarNetworkBean radarNetworkBean) {

    }

    @Override
    public void loadDataFail(String decs) {

    }
}